package com.community.sqlapp.dpsToXmind;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 将文件通过OpenAI兼容接口上传到阿里云百炼平台，保存至平台安全存储空间后获取文件ID
 */
@Component
public class GetFileIdMethodClass {
    @Value("${qianwenvl.vlapi.vlkey}")
    private String dashscopeApiKey;
    @Value("${qianwenvl.vlapi.vlurl}")
    private String dashscopeApiUrl;
    @Value("${qianwenvl.vlapi.qianwenlongurl}")
    private String dashscopeApiLongUrl;

    public String getFileId(String tempFilePath) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(dashscopeApiLongUrl);
        // 设置请求头
        httpPost.setHeader("Authorization", "Bearer " + dashscopeApiKey);
        // 构建 form-data 请求体
        File file = new File(tempFilePath);
        FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
        StringBody stringBody = new StringBody("file-extract", ContentType.TEXT_PLAIN);
        HttpEntity requestEntity = MultipartEntityBuilder.create()
                .addPart("file", fileBody) // 文件字段，字段名为 "file"
                .addPart("purpose", stringBody) // 字符串字段，字段名为 "stringField"
                .build();

        httpPost.setEntity(requestEntity);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity());
        } finally {
            httpClient.close();
        }
    }
}
